//
//  SearchViewController.m
//  Atlantis
//
//  Created by 何恩营 on 14-12-17.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

// 搜索页面
#import "SearchViewController.h"
#import "NetHandler.h"
#import "Album.h"
#import "Music.h"
#import "AlbumDetailsViewController.h"
#import "AlbumCell.h"
#import "MusicCell.h"
#import "UIImageView+WebCache.h"
#import "UIColor+AddColor.h"
#import "PlayViewController.h"

@interface SearchViewController () <UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

//@property (nonatomic, retain)UISearchBar *searchBar;
//@property(nonatomic, retain) NSString *scope;
//@property(nonatomic ,retain) UITableView *tableView;
//@property(nonatomic, retain) UISegmentedControl *seg;

// 表视图
@property (nonatomic, retain) UITableView *searchTableView;
// 数据数组
@property (nonatomic, retain) NSMutableArray *arr;
// 声音数组
@property (nonatomic, retain) NSMutableArray *soundArr;
// 专辑数组
@property (nonatomic, retain) NSMutableArray *albumArr;
// 搜索框
@property (nonatomic, retain) UISearchBar *searchBar;
// 标记显示哪一种cell
@property (nonatomic, assign) NSInteger flag;
// segment
@property (nonatomic, retain) UISegmentedControl *segment;
// 当前请求的是第几页
@property (nonatomic, retain) NSString *page;
// 一共找到多少条记录
@property (nonatomic, assign) NSNumber *numFound;
// 现在是哪个cell
@property (nonatomic, retain) NSString *mark;

@property (nonatomic, retain) NSString *searBarStr;
// 最后更新时间
@property(nonatomic, retain) UILabel *lastUptrackAtLabel;
// 播放次数
@property(nonatomic, retain) UILabel *playsCountsLabel;



@end

@implementation SearchViewController
#pragma mark 释放
// 内存管理
- (void)dealloc
{
    // 表视图
    [_searchTableView release];
    // 数据数组
    [_arr release];
    // 声音数组
    [_soundArr release];
    // 专辑数组
    [_albumArr release];
    // 搜索框
    [_searchBar release];
    // segment
    [_segment release];
    // 当前请求的是第几页
    [_page release];
    // 一共找到多少条记录
    [_numFound release];
    // 现在是哪个cell
    [_mark release];
    [_searBarStr release];
    // 最后更新时间
    [_lastUptrackAtLabel release];
    // 播放次数
    [_playsCountsLabel release];
    [super dealloc];
}


#pragma mark 初始化
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // 现在是哪个cell
        self.mark = @"normal";
        // 标记显示哪一种cell
        self.flag = 2;
        // 页数
        self.page = @"1";
        // 数组
        self.arr = [NSMutableArray array];
        // 声音数组
        self.soundArr = [NSMutableArray array];
        // 专辑数组
        self.AlbumArr = [NSMutableArray array];
    }
    
    return self;
}




#pragma mark 获取网络数据

- (void)handleData
{
    // 创建连接
    NSString *str = @"http://mobile.ximalaya.com/m/hot_search_keys?device=IPhone";
    // 建立连接
    [NetHandler getDataWithURL:str completion:^(NSData *data) {
        // JSON解析
        NSDictionary *sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        // 获取数据
        [self.arr addObjectsFromArray:[sourceDic objectForKey:@"keys"]];
        // 刷新
        [self.searchTableView reloadData];
    }];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 调用数据处理
    [self handleData];
    
    // 设置背景颜色人
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = YES;
    //
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationItem.hidesBackButton = YES;
#pragma mark 设置搜索栏
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 64)];
    view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:view];
    [view release];
    //设置搜索栏  固定在导航栏下边
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10, 20, self.view.bounds.size.width - 30, 30)];
    _searchBar.placeholder=@"搜索声音,专辑";
    _searchBar.delegate = self;
    _searchBar.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.searchBar];
    //是否进行文字纠错  YES. NO;
    _searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
    //单词首字母是否大写  None不大写   Words大写
    _searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _searchBar.searchBarStyle = UISearchBarStyleMinimal;
    
    //让Cancel按钮显示出来
    self.searchBar.showsCancelButton = YES;
    //让搜索栏成为第一响应者
    //[self.searchBar becomeFirstResponder];
    
    [_searchBar release];
    // 视图加载
    [view addSubview:self.searchBar];
    // 标题视图赋值
    self.navigationItem.titleView = view;
    // 设置分段控件的分段按钮
    self.segment = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"专辑",@"声音", nil]];
    self.segment.selectedSegmentIndex = 0;
    self.segment.alpha = 1;
    // 背景颜色
    self.segment.backgroundColor = [UIColor clearColor];
    // 设置大小
    self.segment.frame = CGRectMake(20, 10, self.view.frame.size.width - 40, 30);
    // 触发事件
    [self.segment addTarget:self action:@selector(changeSegment:) forControlEvents:UIControlEventValueChanged];
    // 内存管理
    [_segment release];
    
    
#pragma mark 设置tableView
    // 初始化表视图
    self.searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.bounds.origin.x, 0, self.view.bounds.size.width, self.view.bounds.size.height - 64 - 10) style:UITableViewStylePlain];
    
    // 指定代理人
    self.searchTableView.dataSource = self;
    self.searchTableView.delegate = self;
    // 指定行高
    self.searchTableView.sectionHeaderHeight = 40;
    // 视图加载
    [self.view addSubview:self.searchTableView];
    // 内存管理
    [_searchTableView release];
    
    // 注册cell
    [self.searchTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"normalReuse"];
    //[self.searchTableView registerClass:[MusicCell class] forCellReuseIdentifier:@"SoundsReuse"];
    [self.searchTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"SoundsReuse"];
    
    //[self.searchTableView registerClass:[AlbumCell class] forCellReuseIdentifier:@"AlbumReuse"];
    [self.searchTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"AlbumReuse"];
    

    // 隐藏tabBar
    [self.tabBarController.tabBar setHidden:YES];
    
    
    // Do any additional setup after loading the view.
    
}

//
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    // 取消第一响应者
    [self.searchBar resignFirstResponder];
}



#pragma mark searchBar的协议方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    searchBar.showsCancelButton = YES;
    self.searBarStr = searchText;
    if (self.flag == 1) {
        [self.arr removeAllObjects];
        [self.soundArr removeAllObjects];
        [self getSoundsInfor:searchText];
    } else if (self.flag == 0) {
        
        [self.arr removeAllObjects];
        [self.albumArr removeAllObjects];
        [self getAlbumInfor:searchText];
    } else {
        [self.arr removeAllObjects];
        [self.albumArr removeAllObjects];
        [self getAlbumInfor:searchText];
        self.flag = 0;
    }
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    //显示离开按钮

    return YES;
}

// 取消按钮实现方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    // 返回前一页
    [self.navigationController popViewControllerAnimated:YES];
    
}


#pragma mark tableView的协议方法
// cell的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}

// cell的值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.flag == 2) {
        // 初始化cell
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"normalReuse"];
        cell.textLabel.text = [self.arr objectAtIndex:indexPath.row];
        return cell;
    } else if (self.flag == 1) {
        // 初始化cell
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SoundsReuse"];
        //NSLog(@"//////%@", self.arr);
        cell.textLabel.text = [[self.arr objectAtIndex:indexPath.row] title];
        return cell;
    } else if (self.flag == 0){
        // 初始化cell
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AlbumReuse"];
        cell.textLabel.text = [[self.arr objectAtIndex:indexPath.row] title];

        return cell;
    }

    return nil;
}



- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [NSString stringWithFormat:@"section:%ld", section];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return nil;
    }
    // Create header view and add label as a subview
    UIView *sectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, tableView.bounds.size.height)] autorelease];
    // 背景颜色
    [sectionView setBackgroundColor:[UIColor whiteColor]];
    // sectionView.userInteractionEnabled = YES;
    [sectionView addSubview:self.segment];
    
    return sectionView;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.flag == 2) {
        
        return (self.view.bounds.size.height - 64 - 40) / self.arr.count;
        
    } else if (self.flag == 1) {
        
        return 40;
    } else {
        
        return 40;
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"****%@", [self.mark class]);
    if ([self.mark isEqualToString:@"normal"] && self.searBarStr.length == 0) {
        
        if (self.segment.selectedSegmentIndex == 1) {
            self.mark = @"sound";
            NSString *str = [self.arr objectAtIndex:indexPath.row];
            self.searBarStr = str;
            [self.arr removeAllObjects];
            [self.soundArr removeAllObjects];
            [self.searchTableView reloadData];
            [self getSoundsInfor:str];
            
        } else if (self.segment.selectedSegmentIndex == 0) {
            self.mark = @"album";
            
            NSString *str = [self.arr objectAtIndex:indexPath.row];
            self.searBarStr = str;
            [self.arr removeAllObjects];
            [self.albumArr removeAllObjects];
            [self.searchTableView reloadData];
            self.flag = 0;
            [self getAlbumInfor:str];
        }
    } else if (self.segment.selectedSegmentIndex == 0) {
        
        AlbumDetailsViewController *albumDetailsVC = [[AlbumDetailsViewController alloc] init];
        albumDetailsVC.album = [self.arr objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:albumDetailsVC animated:YES];
        [albumDetailsVC release];
        
    } else if  (self.segment.selectedSegmentIndex == 1) {
        // 创建播放视图 -- 单例
        PlayViewController *playVC = [PlayViewController sharePlayVC];
        //NSLog(@"-----------------%@", self.arr);
        // 传值对象
        playVC.music = [self.arr objectAtIndex:indexPath.row];
        // 专辑数组为空
        playVC.musicArr = nil;
        //NSLog(@"%@", playVC.music.playUrl64);
        // 推出播放界面
        [self.navigationController pushViewController:playVC animated:YES];
    }
    
}

#pragma mark segment的方法

- (void)changeSegment:(UISegmentedControl *)seg
{
    // 如果分段控件下标为0
    if (seg.selectedSegmentIndex == 0) {
        
        self.flag = 0;
        if (self.searchBar.text.length != 0) {
            [self.arr removeAllObjects];
            [self.albumArr removeAllObjects];
            [self.searchTableView reloadData];
            [self getAlbumInfor:self.searchBar.text];
        } else {
            
            [self.arr removeAllObjects];
            [self.albumArr removeAllObjects];
            [self getAlbumInfor:self.searBarStr];
            
        }
    } else if (seg.selectedSegmentIndex == 1) {
        self.flag = 1;
        if (self.searchBar.text.length != 0) {
            // 数组移除
            [self.arr removeAllObjects];
            // 数组移除
            [self.soundArr removeAllObjects];
            
            [self.searchTableView reloadData];
            // 请求声音数据
            [self getSoundsInfor:self.searchBar.text];
            
        } else {
            // 数组移除
            [self.arr removeAllObjects];
            // 数组移除
            [self.soundArr removeAllObjects];
            // 请求声音数据
            [self getSoundsInfor:self.searchBar.text];
            
        }
        
    }
    // 刷新
    [self.searchTableView reloadData];
    
}


#pragma mark 获得声音信息

- (void)getSoundsInfor:(NSString *)str
{
    // 创建连接
    NSString *strPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/s/mobile/search?device=iPhone&condition=%@&page=%@&per_page=20&scope=voice", str, self.page];
    // 建立连接
    [NetHandler getDataWithURL:strPath completion:^(NSData *data) {
        // JSON解析
        NSDictionary *sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        // 获取字典
        NSDictionary *responseDic = [sourceDic objectForKey:@"response"];
        // 赋值
        self.numFound = [responseDic objectForKey:@"numFound"];
        // 获取数组
        NSArray *docsArr = [responseDic objectForKey:@"docs"];
        // 遍历数组
        for (NSDictionary *dic in docsArr) {
            // 初始化对象
            Music *albumDetailsOflist = [[Music alloc] initWithDictionary:dic];
            // 赋值
            [self.soundArr addObject:albumDetailsOflist];
            // 内存管理
            [albumDetailsOflist release];
        }
        // 数组移除
        [self.arr removeAllObjects];
        // 赋值
        [self.arr addObjectsFromArray:self.soundArr];
        //NSLog(@"self.arr:%@", self.arr);
        // 刷新
        [self.searchTableView reloadData];
    }];
 
}

#pragma mark 获得专辑信息

- (void)getAlbumInfor:(NSString *)str
{
    // 创建连接
    NSString *strPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/s/mobile/search?device=iPhone&condition=%@&page=%@&per_page=20&scope=album", str, self.page];
    // 建立连接
    [NetHandler getDataWithURL:strPath completion:^(NSData *data) {
        // JSON解析
        NSDictionary *sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        // 获取字典
        NSDictionary *responseDic = [sourceDic objectForKey:@"response"];
        // 赋值
        self.numFound = [responseDic objectForKey:@"numFound"];
        // 获取数组
        NSArray *docsArr = [responseDic objectForKey:@"docs"];
        // 遍历数组
        for (NSDictionary *dic in docsArr) {
            // 获取对象
            Album *albumOflist = [[Album alloc] initWithDictionary:dic];
            // 判断是否不为0
            if (![[albumOflist.tracksCounts description] isEqualToString:@"0"]) {
                // 若是, 则赋值
                [self.albumArr addObject:albumOflist];
            }
            
            // 内存管理
            [albumOflist release];
        }
        // 数组移除
        [self.arr removeAllObjects];
        // 数组加载
        [self.arr addObjectsFromArray:self.albumArr];
        // 刷新页面
        [self.searchTableView reloadData];
    }];
    
}

// 视图即将结束
- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
